package com.enjoychain.www.security.controller.business.task;

import com.enjoychain.www.security.constant.BusinessTaskType;
import com.enjoychain.www.security.constant.RoleTypeConstant;
import com.enjoychain.www.security.pojo.TaskBuilderPojo;
import com.enjoychain.www.security.pojo.TaskPojo;
import com.enjoychain.www.security.service.ICorpEnvBasicInfoService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Arrays;
import com.enjoychain.www.security.entity.task.TaskInfo;
import com.enjoychain.www.security.service.ITaskInfoService;
import org.springframework.web.bind.annotation.RestController;

import static com.enjoychain.www.security.constant.BusinessTaskType.convertFromString;

/**
 * <p>
 * 任务概要信息表 前端控制器
 * </p>
 *
 * @author ddmonk
 * @since 2023-01-20
 */
@Api(tags = "任务概要信息")
@RestController
@RequestMapping("/security/taskInfo")
public class TaskInfoController {

    @Autowired
    ITaskInfoService service;

    @Autowired
    ICorpEnvBasicInfoService corpEnvBasicInfoService;


    @PreAuthorize("@ss.hasPermi('task:basic:list')")
    @GetMapping(path = "/list", produces = {"application/json"})
    @ApiOperation(value = "获取任务概要信息表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "任务名称",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "keywords", value = "关键字",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "status", value = "任务状态",paramType = "query",  dataType = "Integer"),
            @ApiImplicitParam(name = "type", value = "任务状态",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "corpId", value = "公司id",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "corpName", value = "公司名",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间",paramType = "query",  dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "pageSize", value = "页面记录条数", paramType = "query", dataType = "long")
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response= TaskInfo.class),
    })
    public AjaxResult list(
                            @RequestParam(name = "keywords", required = false) String keywords,
                            @RequestParam(name = "name", required = false) String name,
                            @RequestParam(name = "status", required = false) String status,
                            @RequestParam(name = "type", required = false) String type,
                            @RequestParam(name = "corpId", required = false) String corpId,
                            @RequestParam(name = "corpName", required = false) String corpName,
                            @RequestParam(name = "startTime", required = false) String startTime,
                            @RequestParam(name = "endTime", required = false) String endTime,
                            @RequestParam(name = "pageNum", defaultValue = "1") long pageNo,
                            @RequestParam(name = "pageSize",defaultValue = "10") long pageSize){
        IPage<TaskInfo> entityIPage = new Page<>(pageNo, pageSize);
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        QueryWrapper<TaskInfo> queryWrapper = new QueryWrapper<>();
        if (loginUser.getRoles() != null
                && loginUser.getRoles().size() == 1
                && loginUser.getRoles().get(0).getRoleKey().equals(RoleTypeConstant.CUSTOM)){
            queryWrapper.eq("corp_id",loginUser.getCompanyIds());
        }else {
            //按照角色控制查询权限
            boolean environmentFlag = false;
            boolean securityFlag = false;
            boolean admin = false;
            for (SysRole role : loginUser.getRoles()){
                switch (role.getRoleKey()){
                    case RoleTypeConstant.ADMIN:
                    case RoleTypeConstant.MANAGER:
                        admin = true ;break;
                    case RoleTypeConstant.SECURITY_PATROL: securityFlag = true; break;
                    case RoleTypeConstant.ENVIRONMENT_PATROL: environmentFlag = true; break;
                    default: break;
                }
            }
            if (!admin && environmentFlag && !securityFlag){
                queryWrapper.eq("type",BusinessTaskType.ENVIRONMENT.getValue());
            }
            if (!admin && securityFlag && !environmentFlag){
                queryWrapper.eq("type",BusinessTaskType.SECURITY.getValue());
            }
            if (!environmentFlag && !securityFlag && !admin){
                queryWrapper.eq("type",BusinessTaskType.OTHER.getValue());
            }
            if (StringUtils.isNotEmpty(corpId)) {
                queryWrapper.eq("corp_id", corpId);
            }
            if (StringUtils.isNotEmpty(name)) {
                queryWrapper.like("name", name);
            }
            if (status != null) {
                String[] statusList = status.split(",");
                queryWrapper.in("status", statusList);
            }
            if (StringUtils.isNotEmpty(type)) {
                queryWrapper.eq("type", type);
            }
            if (StringUtils.isNotEmpty(corpName)) {
                queryWrapper.like("corp_name", corpName);
            }
            if (StringUtils.isNotEmpty(keywords)) {
                queryWrapper.like("name", keywords).or().like("corp_name", keywords);
            }

            if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
                queryWrapper.between("start_time", startTime, endTime);
            }
            queryWrapper.orderByDesc("update_time");
        }
        return AjaxResult.success("list-task_info",service.page(entityIPage,queryWrapper));
    }

    @PreAuthorize("@ss.hasPermi('task:basic:query')")
    @GetMapping(value = "{id}", produces = {"application/json"})
    @ApiOperation("获取任务概要信息表详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id",paramType = "path", dataType = "String")
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = TaskInfo.class)
    })
    public AjaxResult getTaskInfoInfo(@PathVariable(value = "id", required = false) String id)
    {
        return AjaxResult.success("get-task_info",service.getTaskDetailById(id));
    }

    @ApiOperation("新建任务")
    @Log(title = "新建任务", businessType = BusinessType.INSERT)
    @PostMapping("/new/{certNo}")
    public AjaxResult newTask(@PathVariable("certNo") String certNo,
                              @RequestParam(name = "type", defaultValue = "environment") String type,
                              @RequestParam(name = "taskType",defaultValue = "b5be0c1a-0e28-47c0-8a42-d76e42a31259",required = false) String taskType) throws Exception{
        try {
            TaskPojo taskPojo = service.buildNewTask(certNo,convertFromString(type),taskType);
            return AjaxResult.success(taskPojo);
        }catch (ServiceException e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("更新信息")
    @Log(title = "更新信息", businessType = BusinessType.UPDATE)
    @PutMapping("/new")
    public AjaxResult updateTaskPojo(@RequestBody TaskPojo taskPojo) throws Exception{
        TaskPojo pojo = service.update(taskPojo, false);
        return AjaxResult.success(pojo);
    }

    @ApiOperation("获取任务")
    @GetMapping("/new/{id}")
    public AjaxResult getTaskPojo(@PathVariable("id") String id) throws Exception{
        TaskPojo pojo = service.getTaskPojo(id);
        return AjaxResult.success(pojo);
    }

    @ApiOperation("删除任务")
    @DeleteMapping("/new/{id}")
    public AjaxResult deleteTaskPojo(@PathVariable("id") String id) throws Exception{
        service.removeByTaskId(id);
        return AjaxResult.success();
    }

    @ApiOperation("更正任务")
    @PutMapping("/new/correct")
    public AjaxResult correctTaskPojo(@RequestBody TaskPojo taskPojo) throws Exception{
        service.update(taskPojo, true);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('task:basic:add')")
    @PostMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("新增任务概要信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = TaskInfo.class),
    })
    @Log(title = "任务概要信息表", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody TaskBuilderPojo pojo){
        //Todo 需要按照类型生成basic与items
        return service.buildTask(pojo.getJobId(),pojo.getCorpId())? AjaxResult.success("add-task_info"): AjaxResult.error("新增任务概要信息表失败");
    }


    @PreAuthorize("@ss.hasPermi('task:basic:update')")
    @PutMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("修改任务概要信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = TaskInfo.class)
    })
    @Log(title = "任务概要信息表", businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody TaskInfo corpBasicInfo,@RequestParam(value = "status",required = false) Integer status){
        String operate = "update-task_info";
        if (status == 1){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            corpBasicInfo.setHandlerId(user.getUserId()+"");
            corpBasicInfo.setHandlerName(user.getNickName());
            corpBasicInfo.setStartTime(LocalDateTime.now());
        }
        if (status == 2 || status == 3){
            corpBasicInfo.setEndTime(LocalDateTime.now());
        }
        service.updateById(corpBasicInfo);
        return AjaxResult.success(operate,service.getTaskPojo(corpBasicInfo.getId()));
    }

    @PreAuthorize("@ss.hasPermi('task:basic:delete')")
    @DeleteMapping(value = "{id}", produces = {"application/json"})
    @ApiOperation("删除任务概要信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    @Log(title = "任务概要信息表", businessType = BusinessType.DELETE)
    public AjaxResult delete(@PathVariable(value = "id", required = false) String id){
        String operate = "delete-task_info";
        String[] ids = id.split(",");
        return service.removeBatchByIdsWithItems(Arrays.asList(ids))?AjaxResult.success(operate) : AjaxResult.error("修改任务概要信息表失败");
    }


    @Log(title = "任务概要信息表", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('task:basic:export')")
    @PostMapping("/export")
    @ApiOperation("导出任务概要信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    public void export(HttpServletResponse response,@RequestParam(name = "corpId", required = false) String corpId){
        QueryWrapper<TaskInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(corpId)) {
            queryWrapper.eq("corp_id",corpId);
        }
        List<TaskInfo> list = service.list(queryWrapper);
        ExcelUtil<TaskInfo> util = new ExcelUtil<TaskInfo>(TaskInfo.class);
        util.exportExcel(response,list, "导出任务概要信息表");
    }





}
